/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.storage.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.storage.common.Constant;
import com.jeesite.modules.storage.service.BrandService;
import com.jeesite.modules.sys.entity.Area;
import com.jeesite.modules.sys.service.AreaService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.modules.storage.entity.FreightTpl;
import com.jeesite.modules.storage.service.FreightTplService;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 运费模板Controller
 */
@Controller(value = "webfreightTpl")
@RequestMapping(value = "${adminPath}/storage/freightTpl")
public class FreightTplController extends BaseController {

	@Autowired
	private FreightTplService freightTplService;

	@Autowired
	private AreaService areaService;

	@Autowired
	private BrandService brandService;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public FreightTpl get(String id, boolean isNewRecord) {
		return freightTplService.get(id, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequestMapping(value = {"list", ""})
	public String list(FreightTpl freightTpl, Model model) {
		model.addAttribute("freightTpl", freightTpl);
		Area area = new Area();
		area.setTreeLevel(0);
		List<Area> areas = areaService.findList(area);
		model.addAttribute("provinces", areas);
		return "modules/storage/freightTpl/list";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<FreightTpl> listData(FreightTpl freightTpl, HttpServletRequest request, HttpServletResponse response) {
		if(StringUtils.isBlank(freightTpl.getBrandId())){
			freightTpl.setBrandId(Constant.DEFAULT_ID);
		}
		freightTpl.setPage(new Page<>(request, response));
		Page<FreightTpl> page = freightTplService.findPage(freightTpl);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequestMapping(value = "form")
	public String form(FreightTpl freightTpl, Model model,HttpServletRequest request) {
		freightTpl.setBrandId(request.getParameter("brandId"));
		if(StringUtils.isNotBlank(freightTpl.getBrandId())){
			freightTpl.setFrom(brandService.getStoreById(freightTpl.getBrandId()));
		}
		model.addAttribute("freightTpl", freightTpl);
		Area area = new Area();
		area.setTreeLevel(0);
		List<Area> areas = areaService.findList(area);
		model.addAttribute("provinces", areas);
		return "modules/storage/freightTpl/form";
	}

	/**
	 * 保存运费模板
	 */
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated FreightTpl freightTpl) {
		try{
			if(StringUtils.isBlank(freightTpl.getBrandId())){
				freightTpl.setBrandId(Constant.DEFAULT_ID);
			}
			freightTplService.save(freightTpl);
			return renderResult(Global.TRUE, text("保存运费模板成功！"));
		}catch (Exception ex){
			return renderResult(Global.FALSE, text(ex.getMessage()));
		}
	}
	
	/**
	 * 删除运费模板
	 */
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(FreightTpl freightTpl) {
		try{
			freightTplService.delete(freightTpl);
			return renderResult(Global.TRUE, text("删除运费模板成功！"));
		}catch (Exception ex){
			return renderResult(Global.FALSE, text(ex.getMessage()));
		}
	}

	/**
	 * 下载导入数据模板
	 */
	@RequestMapping(value = "importTemplate")
	public void importTemplate(HttpServletResponse response) {
		importTemplate(response,"运费 - 大仓库.xlsx");
	}

	/*
	 * 读取Excel到列表
	 */
	private List<FreightTpl> readExcelToList(MultipartFile file){
		try {
			List<FreightTpl> freightTpls = new ArrayList<>();
			Workbook workbook = getWorkbook(file);
			Sheet sheet = workbook.getSheetAt(0);
			for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
				Row row = sheet.getRow(rowNum);
				if (row == null  || row.getLastCellNum() < 4) {
					continue;
				}
				String freightStr = getCellValue(row,3);
				if(StringUtils.isBlank(freightStr)){
					continue;
				}
				FreightTpl freightTpl = new FreightTpl();
				freightTpl.setBrandId(getCellValue(row,0));
				freightTpl.setFrom(getCellValue(row,1));
				freightTpl.setTo(getCellValue(row,2));
				freightTpl.setFreight(Double.parseDouble(freightStr));
				freightTpls.add(freightTpl);
			}
			return freightTpls;
		} catch (Exception ex) {
			throw ex;
		}
	}

	/*
	 * 读取Excel到列表
	 */
	private String check(List<FreightTpl> freightTpls){
		return "";
	}

	/**
	 * 导入数据
	 */
	@ResponseBody
	@PostMapping(value = "importData")
	public String importData(MultipartFile file) {
		try {
			List<FreightTpl> freightTpls = readExcelToList(file);
			String msg = check(freightTpls);
			if(StringUtils.isNotBlank(msg)){
				return renderResult(Global.FALSE, "导入出错:" + msg);
			}
			for (FreightTpl freightTpl : freightTpls){
				freightTpl.setBrandId(brandService.getIdByName(freightTpl.getBrandId()));
				freightTpl.setId(freightTplService.getId(freightTpl.getBrandId(),freightTpl.getFrom(),freightTpl.getTo()));
				freightTplService.save(freightTpl);
			}
			return renderResult(Global.TRUE,"导入成功");
		} catch (Exception ex) {
			return renderResult(Global.FALSE, "导入出错:" + ex.getMessage());
		}
	}
}